# -*-coding: Utf-8 -*-
# @File : tools .py
# author: Chimengmeng
# blog_url : https://www.cnblogs.com/dream-ze/
# Time：2024/7/2
import re
from enum import Enum


class Tools:
    ...


class BasePattern(Enum):
    MOBILE = (r'(\d{3})\d{4}(\d{4})', r"\1****\2")
    EMAIL = (r'(?<=@.)[^@]+(?=\.)', lambda x: '*' * len(x.group(0)))
    CHINESE_NAME = (r'(?<=.{1}).', "*")
    IDENTITY_CARD = (r'(?<=\d{6})\d(?=\d{4})', "*")
    BANK_ID = (r'(?<=\d{4})\d(?=\d{4})', lambda x: '*' * len(x.group(0)))
    BIRTHDAY = (r'(?<=\d{4})\d{2}', '**')

    def __init__(self, pattern: str, replace_data: str):
        self._pattern = pattern
        self._replace_data = replace_data
        super().__init__()

    def pattern(self) -> str:
        return self._pattern

    def replace_data(self) -> str:
        return self._replace_data


class DesensitizeData(object):
    PATTERN_FORMATE = {
        "mobile": r'^1\d{10}$',
        "email": r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
        "identity_card": r'^\d{15}$|^\d{18}$',
        'bank_card': r'^\d{16}$',
        'chinese_name': r'^[\u4e00-\u9fa5]{2,4}$',
        'birthday': r'^\d{4}-\d{2}-\d{2}$'
    }

    def __init__(self, original_data):
        if not isinstance(original_data, str):
            original_data = str(original_data)
        self.original_data = original_data
        self.init_pattern()

    @property
    def desensitize(self):
        if not hasattr(self, '_pattern') or not hasattr(self, "_replace_data"):
            raise Exception("pattern or replace_data is not exist")
        else:
            return re.sub(getattr(self, '_pattern'), getattr(self, '_replace_data'), self.original_data)

    def init_pattern(self):
        for tag, pattern in self.PATTERN_FORMATE.items():
            pattern = re.compile(pattern)
            if re.match(pattern, self.original_data):
                replace_pattern = getattr(BasePattern, tag.upper()).pattern()
                replace_data = getattr(BasePattern, tag.upper()).replace_data()
                setattr(self, "_pattern", replace_pattern)
                setattr(self, "_replace_data", replace_data)
